package com.xcc.java_base.zerocopy;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 传统的拷贝
 */
public class MyOldClient {

    public static void main(String[] args) throws IOException {
        //创建socket连接
        Socket socket = new Socket("localhost", 8888);
        //定义文件路径
        String fileName = "E:\\学习\\springcloud.zip";
        FileInputStream inputStream = new FileInputStream(fileName);
        //创建输出流
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        //定义缓冲区
        byte[] bytes = new byte[1024];
        long readCount = 0;
        long total = 0;
        long startTime = System.currentTimeMillis();
        //TODO 这里要发生2次copy和2次上下文切换
        //copy:1.将磁盘文件通过DMA拷贝到内核 2.将内核文件拷贝到用户(CPU拷贝)
        //上下文切换：1.用户态 -> 内核态  2.内核态->用户态
        while ((readCount = inputStream.read(bytes))>=0) {
            total += readCount;
            //TODO 网络发送：这里发生2此copy 2次上下文切换
            //copy：1.从用户拷贝到socket内核 2.从socket内核通过DMA拷贝到网卡
            //上下文切换：1.用户态->内核态 2.内核态->用户态
            outputStream.write(bytes);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("发送总字节数： "+total+" , 耗时： "+(endTime-startTime)+"ms");
        outputStream.close();
        inputStream.close();
        socket.close();
    }

}
